/**
 * API轮询工具类
 * 用于定时调用API接口，可控制开始、停止和销毁
 */

class ApiPolling {
  /**
   * 创建API轮询实例
   * @param {Function} apiFunction - 要调用的API函数，需要返回Promise
   * @param {number} interval - 轮询间隔，单位为毫秒
   * @param {Function} onSuccess - 成功回调函数，接收API返回的数据
   * @param {Function} onError - 错误回调函数，接收错误信息
   */
  constructor(apiFunction, interval, onSuccess = null, onError = null) {
    this.apiFunction = apiFunction;
    this.interval = interval;
    this.onSuccess = onSuccess;
    this.onError = onError;
    this.timerId = null;
    this.isPolling = false;
  }

  /**
   * 开始轮询
   * @param {boolean} executeImmediately - 是否立即执行一次
   * @returns {ApiPolling} 返回实例本身，支持链式调用
   */
  start(executeImmediately = true) {
    if (this.isPolling) {
      return this;
    }

    this.isPolling = true;

    const executePoll = () => {
      if (!this.isPolling) return;

      this.apiFunction()
        .then(data => {
          if (this.onSuccess) this.onSuccess(data);
        })
        .catch(error => {
          if (this.onError) this.onError(error);
        })
        .finally(() => {
          if (this.isPolling) {
            this.timerId = setTimeout(executePoll, this.interval);
          }
        });
    };

    if (executeImmediately) {
      executePoll();
    } else {
      this.timerId = setTimeout(executePoll, this.interval);
    }

    return this;
  }

  /**
   * 停止轮询
   * @returns {ApiPolling} 返回实例本身，支持链式调用
   */
  stop() {
    this.isPolling = false;
    if (this.timerId) {
      clearTimeout(this.timerId);
      this.timerId = null;
    }
    return this;
  }

  /**
   * 更改轮询间隔
   * @param {number} newInterval - 新的轮询间隔（毫秒）
   * @returns {ApiPolling} 返回实例本身，支持链式调用
   */
  updateInterval(newInterval) {
    this.interval = newInterval;
    if (this.isPolling) {
      this.stop().start(false);
    }
    return this;
  }

  /**
   * 强制立即执行一次API调用，不影响原有的轮询计划
   * @returns {Promise} 返回API调用的Promise
   */
  executeNow() {
    return this.apiFunction()
      .then(data => {
        if (this.onSuccess) this.onSuccess(data);
        return data;
      })
      .catch(error => {
        if (this.onError) this.onError(error);
        throw error;
      });
  }

  /**
   * 销毁实例，停止轮询并清除所有引用
   */
  destroy() {
    this.stop();
    this.apiFunction = null;
    this.onSuccess = null;
    this.onError = null;
  }
}

// Vue组合式API的轮询钩子
export const useApiPolling = (apiFunction, interval, immediate = true) => {
  const polling = new ApiPolling(apiFunction, interval);
  let isSetup = false;

  const setup = (onSuccess, onError) => {
    if (isSetup) return;
    isSetup = true;
    
    polling.onSuccess = onSuccess;
    polling.onError = onError;
    
    if (immediate) {
      polling.start();
    }

    // 在组件卸载时自动销毁
    if (typeof window !== 'undefined') {
      // 确保在浏览器环境中执行
      import('vue').then(({ onBeforeUnmount, getCurrentInstance, onUnmounted }) => {
        const instance = getCurrentInstance();
        if (instance) {
          onUnmounted(() => {
            polling.destroy();
          });
        }
      }).catch(() => {
        console.warn('Vue not available, auto cleanup not registered');
      });
    }
  };

  return {
    start: (executeImmediately = true) => polling.start(executeImmediately),
    stop: () => polling.stop(),
    executeNow: () => polling.executeNow(),
    updateInterval: (newInterval) => polling.updateInterval(newInterval),
    destroy: () => polling.destroy(),
    setup
  };
};

export default ApiPolling; 